<template>
  <div style="width: 100%;height: 100%;">
    <BaseMainSlot :show-tab="true">
      <template v-slot:search-box>
        <SearchForm :form-config="formConfig" :form-data="filterData" @search="search" />
      </template>
      <template v-slot:tab-select>
        <SelectButton :buttonselectlist="buttonselectlist" @nowselectbuttonindex="batchstaumet" />
      </template>
      <template v-slot:btn-box>
        <div class="page-top__todo">
          <CommonBtn @click="reload">刷新</CommonBtn>
        </div>
      </template>

      <template v-slot:table-box>
        <tdtable v-loading="tableLoading" :page="page" :prop-list="propList" :table-data="tableData" :show-index-column="true" :show-select-column="true" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" @handleSelectionChange="handleSelectionChange">
          <template v-slot:processingVolume="{ row }">
            <span v-if="row.processingVolume">{{ row.processingVolume }} {{ row.unitName }}</span>
          </template>
          <template v-slot:actualVolume="{ row }">
            <span v-if="row.actualVolume">{{ row.actualVolume }} {{ row.unitName }}</span>
          </template>
          <template v-slot:expectMaterial="{ row }">
            <el-button v-if="row.batchId" type="text" class="text-btn-cursor" size="small" @click="showMaterial(row)">查看</el-button>
          </template>
          <template v-slot:task="{ row }">
            <el-button v-if="row.batchId" type="text" class="text-btn-cursor" size="small" @click="taskDetail(row)">查看</el-button>
          </template>
          <template v-slot:detail="{ row }">
            <el-button v-if="row.batchId" type="text" class="text-btn-cursor" size="small" @click="detail(row)">查看</el-button>
          </template>
          <template v-slot:batchType="{ row }">
            <span v-if="row.batchType">{{ row.batchType === 'SELF' ? '自主生产' : '委托加工' }}</span>
          </template>
          <template v-slot:generateTime="{ row }">
            <span v-if="row.generateTime">{{ $moment(row.generateTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
          <template v-slot:processTime="{ row }">
            <span v-if="row.startTime">{{ $moment(row.startTime).format('YYYY-MM-DD') }}--{{ $moment(row.endTime).format('YYYY-MM-DD') }}</span>
          </template>
          <template v-slot:actualStartTime="{ row }">
            <span v-if="row.startTime">{{ $moment(row.actualStartTime).format('YYYY-MM-DD') }}--{{ $moment(row.actualEndTime).format('YYYY-MM-DD') }}</span>
          </template>
          <template v-slot:closeEndTime="{ row }">
            <span v-if="row.closeEndTime">{{ $moment(row.closeEndTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
          <template v-slot:finishTime="{ row }">
            <span v-if="row.finishTime">{{ $moment(row.finishTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
          <template v-slot:edit="{ row }">
            <div v-if="row.batchId" class="operate">
              <el-button v-if="row.status === 'CREATE'" type="text" class="text-btn-cursor" size="small" @click="edit(row)">修改</el-button>
              <el-button v-if="row.status === 'TOWARD'" type="text" class="text-btn-cursor" size="small" @click="complete(row)">完成批次</el-button>
              <el-button v-if="row.status === 'TOWARD'" type="text" class="text-btn-cursor cursor-delete" size="small" @click="close(row)">关闭批次</el-button>
            </div>
          </template>
        </tdtable>
      </template>
    </BaseMainSlot>
    <AddEditDialog v-model="addEditShow" :selected-item="selectedItem" :product-list="productList" @reflash="search" />
    <Close v-model="closeShow" :selected-item="selectedItem" @reflash="search" />
    <Complete v-model="completeShow" :selected-item="selectedItem" @reflash="search" />
    <Detail v-model="detailShow" :selected-item="selectedItem" @reflash="search" />
    <MaterialExp v-model="showMaterialList" :list="materialList" />
    <TaskDetail v-model="showTaskDetail" :selected-item="selectedItem" />
  </div>
</template>
<script>
import BaseMainSlot from '@/components/BaseMainSlot/newBaseMainSlot';
import SearchForm from '@/components/searchForm';
import apiProcess from '@/api/processing-management/basic-info-manage/product-process';
import api from '@/api/processing-management/process-batch-manage/process-batch-creation/index';
import tdtable from '@/components/table/index.vue';
import SelectButton from '@/components/selectbutton/index.vue';
import AddEditDialog from '../process-batch-creation/components/add-edit-dialog.vue';
import Close from './components/close.vue';
import Complete from './components/complete.vue';
import Detail from './components/detail.vue';
import TaskDetail from './components/taskDetail.vue';
import MaterialExp from '@/views/processing-management/process-batch-manage/process-batch-creation/components/material-exp.vue';
export default {
  inject: ['reload'],
  components: {
    BaseMainSlot,
    SearchForm,
    tdtable,
    SelectButton,
    AddEditDialog,
    Close,
    Complete,
    Detail,
    MaterialExp,
    TaskDetail
  },
  props: {},
  data() {
    return {
      showTaskDetail: false,
      detailShow: false,
      completeShow: false,
      closeShow: false,
      addEditShow: false,
      buttonselectlist: [
        { name: '未开始', status: 'CREATE' },
        { name: '进行中', status: 'TOWARD' },
        { name: '已完成', status: 'FINISH' },
        { name: '已关闭', status: 'CLOSE' }
      ],
      curTabIndex: 0,
      curStatus: null,
      showMaterialList: false,
      materialList: [],
      tableData: [],
      tableLoading: false,
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      formConfig: [
        {
          label: '批次名称',
          prop: 'batchName',
          type: 'input'
        },
        {
          label: '批次号',
          prop: 'batchNo',
          type: 'input'
        },
        {
          label: '加工产品',
          prop: 'productId',
          type: 'select',
          options: [],
          optionKey: { label: 'productName', value: 'productId' }
        },
        {
          label: '加工时间',
          prop: 'date',
          type: 'daterange'
        }
      ],
      filterData: {},
      selectedItem: null,
      productList: [],
      propListOrg: [
        { prop: 'batchName', label: '批次名称', minWidth: '100' },
        { prop: 'batchNo', label: '批次号', minWidth: '110' },
        { prop: 'productName', label: '产品名称', minWidth: '100' },
        {
          prop: 'processingVolume',
          label: '预期加工量',
          minWidth: '100',
          slotName: 'processingVolume'
        },
        {
          prop: 'actualVolume',
          label: '实际加工量',
          minWidth: '100',
          slotName: 'actualVolume'
        },
        {
          prop: 'expectMaterial',
          label: '预期原料量',
          minWidth: '100',
          slotName: 'expectMaterial'
        },
        {
          prop: 'batchType',
          label: '批次类型',
          minWidth: '100',
          slotName: 'batchType'
        },
        {
          prop: 'startTime',
          label: '预期加工时间(开始-结束)',
          minWidth: '260',
          slotName: 'processTime'
        },
        {
          prop: 'actualStartTime',
          label: '实际加工时间(开始-结束)',
          minWidth: '260',
          slotName: 'actualStartTime'
        },
        { prop: 'generateTime', label: '创建时间', minWidth: '200', slotName: 'generateTime' },
        { prop: 'task', label: '关联作业任务', minWidth: '150', slotName: 'task' },
        { prop: 'detail', label: '查看详情', minWidth: '100', slotName: 'detail' },
        { prop: 'finishTime', label: '完成时间', minWidth: '200', slotName: 'finishTime' },
        { prop: 'closeEndTime', label: '关闭时间', minWidth: '200', slotName: 'closeEndTime' },
        { prop: 'edit', label: '操作', minWidth: '200', slotName: 'edit' }
      ],
      propList: []
    };
  },
  watch: {},
  created() {
    this.curStatus = this.buttonselectlist[this.curTabIndex];
    this.setPropList();
    this.getProductList();
    this.search();
  },
  methods: {
    getProductList() {
      apiProcess.queryByCondition({ status: 1 }).then(res => {
        if (res.code === 1) {
          this.productList = res.data;
          this.formConfig.find(i => i.prop === 'productId').options = res.data;
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedList = list.map(item => {
        return item.batchId;
      });
      if (this.selectedList && this.selectedList.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },
    handleSizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.search();
    },
    handleCurrentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.search();
    },
    search() {
      const { buttonselectlist, curTabIndex } = this;
      const { currentPage, pageSize } = this.page;
      const filterData = JSON.parse(JSON.stringify(this.filterData));
      if (filterData.date && filterData.date.length !== 0) {
        filterData.startTime = this.$moment(filterData.date[0]).format('YYYY-MM-DD HH:mm:ss');
        filterData.endTime = this.$moment(filterData.date[1]).format('YYYY-MM-DD HH:mm:ss');
      }
      delete filterData.date;
      filterData.status = buttonselectlist[curTabIndex].status;
      if (filterData.status === '') {
        delete filterData.status;
      }
      this.tableLoading = true;
      api
        .queryPageByCondition({
          page: currentPage,
          size: pageSize,
          entity: {
            ...filterData
          }
        })
        .then(res => {
          if (res.code === 1) {
            this.tableData = this.$utils.addblankmet(res.data.content, pageSize);
            this.page.total = res.data.totalElements;
            if (res.data.content.length === 0 && this.page.currentPage !== 1) {
              this.page.currentPage--;
              this.search();
            }
          }
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    showMaterial(row) {
      this.queryBomByProduct(row);
      this.showMaterialList = true;
    },
    queryBomByProduct(row) {
      const { processingVolume, productId } = row;
      if (processingVolume && productId) {
        api.queryBomByProduct(processingVolume, productId).then(res => {
          if (res.code === 1) {
            this.materialList = res.data;
          }
        });
      }
    },
    batchstaumet(index) {
      this.curTabIndex = index;
      this.curStatus = this.buttonselectlist[this.curTabIndex];
      this.setPropList();
      this.handleCurrentChange(1);
    },
    edit(item) {
      this.selectedItem = JSON.parse(JSON.stringify(item));
      this.addEditShow = true;
    },
    close(item) {
      this.selectedItem = JSON.parse(JSON.stringify(item));
      this.closeShow = true;
    },
    complete(item) {
      this.selectedItem = JSON.parse(JSON.stringify(item));
      this.completeShow = true;
    },
    detail(item) {
      this.selectedItem = JSON.parse(JSON.stringify(item));
      this.detailShow = true;
    },
    taskDetail(item) {
      this.selectedItem = JSON.parse(JSON.stringify(item));
      this.showTaskDetail = true;
    },
    setPropList() {
      const { propListOrg } = this;
      const { status } = this.curStatus;
      if (status === 'CREATE') {
        this.propList = propListOrg.filter(item => !['actualStartTime', 'actualVolume', 'closeEndTime', 'finishTime', 'task', 'detail'].includes(item.prop));
      }
      if (status === 'TOWARD') {
        this.propList = propListOrg.filter(item => !['actualStartTime', 'actualVolume', 'closeEndTime', 'finishTime', 'generateTime', 'detail'].includes(item.prop));
      }
      if (status === 'FINISH') {
        this.propList = propListOrg.filter(item => !['expectMaterial', 'startTime', 'closeEndTime', 'task', 'generateTime', 'edit'].includes(item.prop));
      }
      if (status === 'CLOSE') {
        this.propList = propListOrg.filter(item => !['expectMaterial', 'startTime', 'finishTime', 'task', 'generateTime', 'edit'].includes(item.prop));
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.content-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
}
</style>
